package gateway.com.filter;

import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * @author: jaykim
 * @created: 2023/11/17
 */
@Component
public class TimeGatewayFilterFactory extends AbstractGatewayFilterFactory<TimeGatewayFilterFactory.config> {

    //Time = true,1,hello
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("show");
    }

    public TimeGatewayFilterFactory(){
        super(config.class);
    }

    //拦截到之后会调用
//    @Override
//    public GatewayFilter apply(NameConfig config) {
//        return new GatewayFilter() {
//            @Override
//            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//                //前置逻辑
//                System.out.println("前值逻辑");
//                return chain.filter(exchange).then(Mono.fromRunnable(()->{
//                    //后置逻辑
//                    System.out.println("后置逻辑");
//                }));
//            }
//        };
//    }

    @Override
    public GatewayFilter apply(config config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                //前置逻辑
                System.out.println("前值逻辑");
                return chain.filter(exchange).then(Mono.fromRunnable(()->{
                    //后置逻辑
                    System.out.println("后置逻辑");
                }));
            }
        };
    }

    @Getter
    @Setter
    static class config{
        private boolean show;
    }
}
